package com.beamfield.controller.common;

import com.beamfield.common.ApiResult;
import com.beamfield.common.CommonUtils;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.FileInfo;
import com.beamfield.modelVo.FileInfoVo;
import com.beamfield.service.manage.sys.FileService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;


@Controller
public class FileController  {

	private static final Logger log = LoggerFactory.getLogger(FileController.class);
	@Resource
	private FileService fileService;

	@Value("${uploadFilePath}")
	private String uploadFilePath;

	@Value("D:\\upload\\temp\\")
	private String uploadTempPath;

	@Value("${webRootUrl}")
	private String webRootUrl;
	
	@Value("${fileRootUrl}")
	private String fileRootUrl;

	@RequestMapping(value = "/cms/common/chinesetopinyin")
	@ResponseBody
	public ApiResult chinesetopinyin(String value){
		if(StringUtils.isEmpty(value)){
			return new ApiResult();
		}
		return new ApiResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(), CommonUtils.getPinYin(value));
	}

	@RequestMapping(value = "/cms/common/upload_file",method = RequestMethod.POST)
	@ResponseBody
	@Transactional(readOnly = false, propagation = Propagation.SUPPORTS)
	public long saveFile(@RequestParam("file") MultipartFile file) {
		int fileid = 0;
		try {
			if (file != null) {
				String myFileName = file.getOriginalFilename();
				if (!CommonUtils.isEmptyString(myFileName)) {
					String savePath = CommonUtils.getTimeFormat(new Date(), "yyyyMMdd") + File.separator;
					String path = uploadFilePath+ savePath;
					// 定义上传路径
					CommonUtils.checkPath(path);
					int index = myFileName.lastIndexOf(".");
					String extension = "";
					if (index > 0) {
						extension = myFileName.substring(index, myFileName.length());
					}
//					String filename = CommonUtils.getTimeFormat(new Date(), "yyyyMMddhhmmssSSS") + "_"
//							+ (int) (Math.random() * 100) + extension;
					OutputStream out = new FileOutputStream(path + myFileName);
					byte[] b = null;
					if(file.getSize()>200*1024){
						if(".jpg".equals(extension.toLowerCase())||".jpeg".equals(extension.toLowerCase())){
							Thumbnails.of(file.getInputStream()).scale(0.9f).outputQuality(0.4).toOutputStream(out);
						}
						if(".png".equals(extension.toLowerCase())){
							Thumbnails.of(file.getInputStream()).scale(0.6f).outputQuality(0.5).toOutputStream(out);
						}
						else{
							b = file.getBytes();
						}
					}else{
						b = file.getBytes();
					}
					if(b != null){
						out.write(b);
					}
					out.flush();
					out.close();

					// 文件表留档
					FileInfo fileInfo = new FileInfo();
					fileInfo.setAdd_time(new Date());
					fileInfo.setFile_path(savePath);
					fileInfo.setOriginal_name(myFileName);
					fileInfo.setFormer_name(myFileName);
					fileInfo = fileService.saveFileInfo(fileInfo);
					// fileid = fileInfo.getFileid();
					return fileInfo.getFileid();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileid;
	}


	@RequestMapping(value = "/cms/common/upload_fileReturnFileInfo",method = RequestMethod.POST)
	@ResponseBody
	@Transactional(readOnly = false, propagation = Propagation.SUPPORTS)
	public FileInfo saveFileReturnFileInfo(@RequestParam("file") MultipartFile file) {
		FileInfo fileInfo = new FileInfo();
		try {
			if (file != null) {
				String myFileName = file.getOriginalFilename();
				if (!CommonUtils.isEmptyString(myFileName)) {
					String savePath = CommonUtils.getTimeFormat(new Date(), "yyyyMMdd") + File.separator;
					String path = uploadFilePath+ savePath;
					// 定义上传路径
					CommonUtils.checkPath(path);
					int index = myFileName.lastIndexOf(".");
					String extension = "";
					if (index > 0) {
						extension = myFileName.substring(index, myFileName.length());
					}
					String filename = CommonUtils.getTimeFormat(new Date(), "yyyyMMddhhmmssSSS") + "_"
							+ (int) (Math.random() * 100) + extension;
					OutputStream out = new FileOutputStream(path + myFileName);
					byte[] b = null;
					if(file.getSize()>200*1024){
						if(".jpg".equals(extension.toLowerCase())||".jpeg".equals(extension.toLowerCase())){
							Thumbnails.of(file.getInputStream()).scale(0.9f).outputQuality(0.4).toOutputStream(out);
						}
						if(".png".equals(extension.toLowerCase())){
							Thumbnails.of(file.getInputStream()).scale(0.6f).outputQuality(0.5).toOutputStream(out);
						}
						else{
							b = file.getBytes();
						}
					}else{
						b = file.getBytes();
					}
					if(b != null){
						out.write(b);
					}
					out.flush();
					out.close();

					// 文件表留档
					fileInfo.setAdd_time(new Date());
					fileInfo.setFile_path(savePath);
					fileInfo.setOriginal_name(myFileName);
					fileInfo.setFormer_name(myFileName);
					FileInfo fileInfo1 = fileService.saveFileInfo(fileInfo);
					// fileid = fileInfo.getFileid();
					String fielUrl = CommonUtils.getFielUrl(fileInfo1);
					fileInfo1.setOriginal_name(myFileName);
					fileInfo1.setFile_path(fielUrl);
					return fileInfo1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileInfo;
	}
	
	/**
	 * 
	 * @Description 图片上传
	 * @param request
	 * @param response
	 * @return String  要以String类型返回，不然会返回<h1>HTTP Status 406 - </h1>........配置文件中也需要配置，避免IE中变成下载项
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadImg", produces = "text/html; charset=UTF-8")  
	public String upDateHeadImg(HttpServletRequest request, HttpServletResponse response, 
			HttpSession session) {
		ApiResult result = new ApiResult();
		try {
			request.setCharacterEncoding("utf-8");
			Map<String, Object> file_id = getImageInfo(request);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("fileid",file_id.get("fileid"));
			map.put("fileurl",file_id.get("fileurl"));
			result.setResult(map);
			return com.alibaba.fastjson.JSONObject.toJSONString(result);
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode("2");
			result.setMessage("服务器端异常");
			return com.alibaba.fastjson.JSONObject.toJSONString(result);
		}
	}
	

	/**
	 * 上传图片
	 */
	@ResponseBody
	@RequestMapping("/cms/getImageInfo")
	public Map<String, Object> getImageInfo(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			try {
				while (iter.hasNext()) {
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						try {
							if (file != null) {
								// 取得当前上传文件的文件名称
								String myFileName = file.getOriginalFilename();
								// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
								if (!CommonUtils.isEmptyString(myFileName)) {
									int index = myFileName.lastIndexOf(".");
									String extension = "";
									if (index > 0) {
										extension = myFileName.substring(index, myFileName.length());
									}
									String savePath = CommonUtils.getTimeFormat(new Date(), "yyyyMMdd") + File.separator;
									String path = uploadFilePath + savePath;
									// 定义上传路径
									CommonUtils.checkPath(path);

									String filename = CommonUtils.getTimeFormat(new Date(), "yyyyMMddhhmmssSSS") + "_"
											+ (int) (Math.random() * 100) + extension;
									OutputStream out = new FileOutputStream(path + myFileName);
									byte[] b = null;
									if(file.getSize()>200*1024){
										if(".jpg".equals(extension.toLowerCase())||".jpeg".equals(extension.toLowerCase())){
											Thumbnails.of(file.getInputStream()).scale(0.9f).outputQuality(0.4).toOutputStream(out);
										}
										if(".png".equals(extension.toLowerCase())){
											Thumbnails.of(file.getInputStream()).scale(0.6f).outputQuality(0.5).toOutputStream(out);
										}
									}else{
										b = file.getBytes();
									}
									if(b != null){
										out.write(b);
									}
									out.flush();
									out.close();
//									Date now = new Date();
//									String savePath = CommonUtils.getDateFormat(now, "yyyyMMdd") + File.separator;
//									String dealerImgPath = CommonUtils.getProperty("dealerImgPath") + savePath;
//									// 定义上传路径
//									CommonUtils.checkPath(dealerImgPath);
//									String extension = myFileName.substring(myFileName.lastIndexOf(".")).toLowerCase();
//									String filename = CommonUtils.getDateFormat(now, "yyyyMMddhhmmssSSS") + "_"
//											+ (int) (Math.random() * 100) + extension;
//									File localOriginFile = new File(dealerImgPath + filename);
//									file.transferTo(localOriginFile);
									// 文件表留档
									// 文件表留档
									FileInfo fileInfo = new FileInfo();
									fileInfo.setAdd_time(new Date());
									fileInfo.setFile_path(savePath);
									fileInfo.setFormer_name(myFileName);
									fileInfo.setOriginal_name(myFileName);
									fileInfo = fileService.saveFileInfo(fileInfo);
									String url =fileRootUrl  + fileInfo.getFile_path() + fileInfo.getOriginal_name();
									url =  url.replace(File.separatorChar, '/');
									map.put("fileid", fileInfo.getFileid());
									map.put("fileurl", url);
									return map;
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
							return null;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}



}
